﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using ICSharpCode.TextEditor;
using ICSharpCode.TextEditor.Gui.CompletionWindow;
using ICSharpCode.TextEditor.Document;
using ICSharpCode.TextEditor.Actions;

namespace Bing.Studio
{
    public partial class FrmTemplateEdit : BaseForm
    {
        private static int _index = 1;

        private FileInfo _file;

        public Boolean IsSaved { get { return !(_file == null); } }

        public FrmTemplateEdit()
        {
            InitializeComponent();
        }

        public FrmTemplateEdit(FileInfo file)
        {
            _file = file;

            InitializeComponent();
        }

        /****************************************************************************************************/

        private void OpenTemplate()
        {
            using (var stream = _file.OpenText())
            {
                this.textEditorControl1.Text = stream.ReadToEnd();
            }
            this.TabText = _file.Name;
            this.Text = _file.Name;
        }

        public void Save()
        {
            File.WriteAllText(_file.FullName, textEditorControl1.Text, Encoding.Default);
            if (this.TabText.IndexOf("*") > 0)
            {
                this.TabText = this.TabText.Replace("*", "");
            }
        }

        public void SaveAs(string strFileName)
        {
            _file = new FileInfo(strFileName);
            Save();
        }

        /****************************************************************************************************/

        private void FrmTemplateEdit_Load(object sender, EventArgs e)
        {
            this.textEditorControl1.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy("C#");
            this.textEditorControl1.Encoding = Encoding.Default;

            if (!(_file == null))
            {
                OpenTemplate();
            }
            else
            {
                this.TabText = String.Format("Template_{0}.tt", (_index++));
                this.Text = this.TabText;
            }  
        }

        private void textEditorControl1_TextChanged(object sender, EventArgs e)
        {
            if (this.TabText != null && this.TabText.IndexOf("*") < 0)
            {
                this.TabText += "*";
            }
        }

        /****************************************************************************************************/
    }
}
